package fr.cdj.thebox.server;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mindrot.jbcrypt.BCrypt;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fr.cdj.thebox.client.services.LoginService;
import fr.cdj.thebox.shared.AccessDeniedException;
import fr.cdj.thebox.shared.User;
import fr.cdj.thebox.shared.WrongLoginException;

public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {

	private static final long serialVersionUID = -4548167385862822185L;

	@Override
	public User loginServer(String name, String password) throws WrongLoginException {
		User user = null;

		if (name.equals("peon") && BCrypt.checkpw(password, BCrypt.hashpw("peon", BCrypt.gensalt()))) {
			user = new User();
			user.setLogin("peon");
			user.setAdmin(false);
		} else if (name.equals("stan") && BCrypt.checkpw(password, BCrypt.hashpw("trouduc", BCrypt.gensalt()))) {
			user = new User();
			user.setLogin("stan");
			user.setAdmin(true);
		} else {
			throw new WrongLoginException();
		}

		storeUserInSession(user);

		return user;
	}

	@Override
	public User loginFromSessionServer() {
		return getUserAlreadyFromSession();
	}

	@Override
	public void logout() {
		deleteUserFromSession();
	}

	@Override
	public boolean changePassword(String name, String newPassword) throws AccessDeniedException {
		throw new AccessDeniedException();
	}

	private User getUserAlreadyFromSession() {
		User user = null;
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		Object userObj = session.getAttribute("user");
		if (userObj != null && userObj instanceof User) {
			user = (User) userObj;
		}
		return user;
	}

	private void storeUserInSession(User user) {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession(true);
		user.setSessionId(session.getId());
		session.setAttribute("user", user);
	}

	private void deleteUserFromSession() {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		session.removeAttribute("user");
	}

}
